#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while(true)
    {
        snprintf(buffer, sizeof(buffer), "I am child, pid: %d, cnt: %d", getpid(), cnt);
        write(wfd, buffer, strlen(buffer));
        cnt++;
        sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        buffer[0] = 0;
        int n = read(rfd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = '\0';
            std::cout << "Child say: " << buffer << std::endl;
        }
    }
}

int main()
{
    std::cout << "管道" << std::endl;
    int fds[2]; // fds[0]读, fds[1]写
    int n = pipe(fds);
    if (n < 0)
    {
        perror("pipe alloction error!");
        return 1;
    }

    // std::cout << "fds[0]: " << fds[0] << std::endl;
    // std::cout << "fds[1]: " << fds[1] << std::endl;
    // 子进程写，父进程读
    int id = fork();
    if (id == 0)
    {
        // 子进程
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
    }
    else
    {
        // 父进程
        close(fds[1]);
        FatherRead(fds[0]);
        close(fds[0]);
        waitpid(id, nullptr, 0);
    }

    return 0;
}